<template>
  <div class="detail">
    <div class="form">
      <div class="title item">
        <span class="title-item name">{{ o.name }}</span>
        <span class="title-item point">
          <img src="../../../assets/point.png" alt="">
          <span class="value">积分：{{ o.point }}分</span>
        </span>
      </div>
      <div class="complexity item">
        <span class="label">难度系数：</span>
        <span class="value">{{ complexity[o.difficulty - 1] }}</span>
      </div>
      <div class="source item">
        <span class="label">题目来源：</span>

        <span class="value">{{ o.source }}</span>
      </div>
      <div class="description item">
        <span class="label">题目表述：</span>
        <span class="value">{{ o.description }}</span>
      </div>
      <div class="image-dev" v-if="o.check_flag === 1">
        <div class="image item" v-if="!running">
          <span class="label">题目场景：</span>
          <span class="start-button" @click="start_container">启动在线场景</span>
        </div>
        <div class="image item" v-else-if="running">
          <span class="label">题目场景：</span>
          <span>
            <div class="public_port">{{ running_container.public_port }}</div>
            <div class="timer">
              <span class="label">倒计时:</span>
              <span>{{ remaining_time }}</span>
            </div>
            <el-popconfirm title="确定要删除场景吗？" @confirm="remove_container">
              <div class="delete" slot="reference">删除场景</div>
            </el-popconfirm>
          </span>
        </div>
      </div>
      <div class="file-dev" v-else-if="o.check_flag === 2">
        <div class="file item" v-if="!running">
          <span class="label">题目附件：</span>
          <a class="download-button" :href="`${this.$request.baseURL}${o.file}`" download target="_blank">附件</a>
        </div>
      </div>
    </div>

    <div class="answer" v-if="!is_cheked">
      <div class="input">
        <input type="text" class="flag" name="flag" placeholder="flag...." v-model="flag">
      </div>
      <div class="button">
        <input type="submit" value="提交" @click="check_flag">
      </div>
    </div>

    <div class="answer done" v-else>
      <div class="button">
        <input type="submit" value="题目已答对">
      </div>
    </div>

    <el-dialog title="启动失败" :visible.sync="dialogVisible">
      <span>已启动 {{ running_container.image.name }} 的环境，是否将其关闭并启动当前容器？</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="remove_container(true)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'Detail',
  data() {
    return {
      is_cheked: false,
      o: {
        id: 0,
        name: '',
        point: 0,
        difficulty: '',
        source: '',
        description: '',
        check_flag: 0,
        file: {
          name: ""
        },
      },
      running: false,
      running_container: {
        id: 0,
        container_id: '',
        image: {
          name: ''
        },
        name: '',
        public_port: '',
        username: '',
        create_time: '',
      },
      remaining_time: '00:00:00',
      complexity: ['新手', '入门', '简单', '普通', '困难'],
      interval: null,
      flag: '',
      dialogVisible: false,
    };
  },
  created() {
    this.get_detail();
  },
  methods: {
    check_self_is_running() {
      if (this.running_container.image.id === this.o.id) {
        this.running = true;
        this.calc_remaining_time(this.running_container.create_time);
        let self = this;
        this.interval = setInterval(function () {
          self.calc_remaining_time(self.running_container.create_time);
        }, 1000);
      }
    },
    check_flag() {
      this.$request.exec('post', 'check_flag', {
        'image_id': this.o.id,
        'flag': this.flag
      }, this)
        .then((res) => {
          if (res.code === 1) {
            this.is_cheked = true;
            this.$message.success(res.msg);
            this.$store.commit('update_checked', res.data);
            this.channels.$emit('update_checked');
          }
        })
        .catch((res) => {
          this.$message.error(res.data.msg);
        });
    },
    calc_remaining_time(date1) {
      date1 = new Date(new Date(date1).getTime() + this.timing * 60 * 60 * 1000);

      let date2 = new Date();    //结束时间
      let date3 = date1.getTime() - date2.getTime();

      //计算出小时数
      let leave1 = date3 % (24 * 3600 * 1000);
      let hours = this.format_time(Math.floor(leave1 / (3600 * 1000)));

      //计算相差分钟数
      let leave2 = leave1 % (3600 * 1000);
      let minutes = this.format_time(Math.floor(leave2 / (60 * 1000)));

      //计算相差秒数
      let leave3 = leave2 % (60 * 1000);
      let seconds = this.format_time(Math.round(leave3 / 1000));

      if (parseInt(hours) <= 0 && parseInt(minutes) <= 0 && parseInt(seconds) <= 0) {
        this.running = false;
        clearInterval(this.interval);
      }

      this.remaining_time = `${hours}:${minutes}:${seconds}`;
    },
    format_time(s) {
      return (s < 10) ? ('0' + s) : s;
    },
    get_running_container() {
      this.$request.exec('get', `get_running_container`, null, this)
        .then((res) => {
          if (res.data.container) {
            this.running_container = res.data.container;
            this.timing = res.data.remaining_time;
            this.check_self_is_running();
          }
        });
    },
    start_container() {
      this.$request.exec('post', `run_container`, { 'id': this.o.id }, this)
        .then((res) => {
          if (res.code === 2) {
            // this.$message.warning(res.msg);
            this.dialogVisible = true;

            return;
          }

          this.$message.success(res.msg);

          this.running_container = res.data.container;
          this.timing = res.data.remaining_time;

          this.check_self_is_running();
        })
        .catch((res) => {
          this.$message.error(res.data.msg);
        });
    },
    get_detail() {
      if (this.$route.query.id) {
        let id = (this.$route.query.id).trim();
        id = parseInt(id);
        this.$request.exec('get', `get_image_detail?id=${id}`, null, this)
          .then((res) => {
            this.o = res.data;

            let userinfo = this.$store.getters.userinfo;
            let checked = userinfo.checked;

            for (let i in checked) {
              let image = checked[i].image;
              if (image.id === this.o.id) {
                this.is_cheked = true;
              }
            }

            this.get_running_container();
          })
          .catch((res) => {
            this.$message.error(res.data.msg);
          });
      } else {
        this.$router.push('/');
      }
    },
    remove_container(restart = false) {
      this.$request.exec('post', 'remove_container', null, this)
        .then((res) => {
          this.running_container = {
            id: 0,
            container_id: '',
            image: {
              name: ''
            },
            name: '',
            public_port: '',
            username: '',
            create_time: '',
          };
          this.running = false;

          if (restart === true) {
            this.start_container();
            this.dialogVisible = false;
            return;
          }

          clearInterval(this.interval);

          this.$message.success(res.msg);
        })
        .catch((res) => {
          if (res.data.code === 2) {
            this.running_container = {
              id: 0,
              container_id: '',
              image: {
                name: ''
              },
              name: '',
              public_port: '',
              username: '',
              create_time: '',
            };
            this.running = false;
            clearInterval(this.interval);

            this.$message.success(res.data.msg);
          }
        });
    }
  },
};
</script>

<style scoped>
.detail {
  position: relative;
  color: #ffffff;
  font-size: 1vw;
  background: url("../../../assets/detail/background.png") 0 0 / 100% 100%;
  width: 84vw;
  margin: 1vw auto 0 auto;
  padding: 2vw 4vw;
  min-height: 37vw;

}

.form * {
  vertical-align: middle;
}

.form * * {
  vertical-align: middle;
}

.item {
  display: flex;
  margin-bottom: 1.5vw;
}

.title .title-item {
  width: 50%;
  display: inline-block;
}

.title .title-item:last-child {
  text-align: right;
}

.title .name {
  font-size: 2vw;
  font-family: PingFang-SC-Bold;
}

.point img {
  width: 1.5vw;
  margin-right: 0.5vw;
}

.point span {
  font-size: 1.2vw;
}

.item {
  max-width: 65%;
}

.title.item {
  display: block;
  max-width: 100%;
}

.item .label {
  white-space: nowrap;
}

.complexity span:last-child {
  border: 0.1vw solid #97feff;
  font-size: .8vw;
  padding: 0.2vw 1.5vw;
  /* background: #2affe138; */
  color: #97feff;
  user-select: none;
}

.source span:last-child {
  border: 0.1vw solid #97feff;
  padding: 0.2vw 1.5vw;
  color: #97feff;
  font-size: .8vw;
  user-select: none;
}

.image span.start-button {
  border: .15vw solid rgb(151 255 224);
  font-size: .8vw;
  padding: .4vw 1.5vw;
  background: rgb(151 255 171 / 18%);
  cursor: pointer;
  user-select: none;
}

.image span.start-button:hover {
  background: rgb(151 255 171 / 31%);
}

.download-button {
  border: .15vw solid rgb(151 255 224);
  font-size: .8vw;
  padding: .4vw 1.5vw;
  background: rgb(151 255 171 / 18%);
  cursor: pointer;
  user-select: none;
  color: #ffff;
}

.download-button:hover {
  background: rgb(151 255 171 / 31%);
  text-decoration: none;
}

.answer {
  text-align: center;
  position: absolute;
  bottom: 2vw;
  width: calc(100% - 4vw * 2);
}

.answer.done {
  bottom: 3vw;
}

.answer input[type="text"] {
  border: solid 1px #59b8f4;
  background: none;
  color: #ffff;
  padding: 0.4vw 0.8vw;
  width: 60%;
  font-size: .9vw;
  margin-bottom: 1vw;
  font-family: DIN-Bold;
  outline: none;
}

.answer input[type="submit"] {
  background: url("../../../assets/detail/submit.png") 0 0 / 100% 100%;
  padding: 0.8vw 2.6vw;
  border: none;
  color: #fff;
  font-size: .85vw;
  cursor: pointer;
}

.answer input[type="submit"]:hover {
  background: url("../../../assets/detail/submit_hover.png") 0 0 / 100% 100%;
}

.answer.done input[type="submit"] {
  background: url("../../../assets/detail/submit_done.png") 0 0 / 100% 100%;
  padding: 1vw 2vw;
  border: none;
  color: #fff;
  font-size: .85vw;
  cursor: pointer;
}

input::-webkit-input-placeholder {
  font-family: DIN-Bold;
  color: #b3b3b3;
  font-size: .94vw;
}

input::-moz-placeholder { /* Mozilla Firefox 19+ */
  color: #b3b3b3;
  font-family: DIN-Bold;
  font-size: .94vw;
}

input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
  color: #b3b3b3;
  font-family: DIN-Bold;
  font-size: .94vw;
}

input:-ms-input-placeholder { /* Internet Explorer 10-11 */
  color: #b3b3b3;
  font-family: DIN-Bold;
  font-size: .94vw;
}

.timer {
  margin: .5vw 0;
}

.timer .label {
  margin-right: .3vw;
}

.delete {
  border: solid 1px #f45959ba;
  color: #ffffff;
  text-align: center;
  padding: 0.3vw 1.2vw;
  font-size: .8vw;
  display: inline-block;
  background: #f45959ba;
  cursor: pointer;
  user-select: none;
}

.delete:hover {
  background: #f45959e6;
}

.value {
  font-size: .8vw;
}

</style>
